#!/bin/sh
# add regular user(s) assigning passwords and attributes of power

# NB: care that the utilities exist; shadow-utils is warranted

add_user() {
	useradd -m "$1" &&
	usermod -p "" "$1" &&
	if [ -n "$GLOBAL_GROUPS" ]; then	# some of them might be missing
		for group in $GLOBAL_GROUPS; do
			usermod -a --groups "$group" "$1" ||:
		done
	fi ||
	echo "*** failed to add user '$1'"
}

set_password() { echo "$1:$2" | chpasswd; }

set_admin() { usermod -a --groups "wheel" "$1"; }

# NB: one must care to purge this from LiveCD if it's installed permanently
set_sudo() {
	[ ! -w "/etc/sudoers" ] ||
		echo "$1	ALL=(ALL) ALL" >> "/etc/sudoers"
}

# chpasswd is intended for batch use but that would be less comprehensible
[ -z "$GLOBAL_USERS" ] ||
	echo "$GLOBAL_USERS" \
	| tr ' ' '\n' \
	| while IFS=':' read login passwd admin sudo; do
		add_user "$login"
		[ -z "$passwd" ] || set_password "$login" "$passwd"
		[ -z "$admin" ] || set_admin "$login"
		[ -z "$sudo" ] || set_sudo "$login"
	done

# create special user
[ -z "$GLOBAL_SPEC_USER" ] ||
	echo "$GLOBAL_SPEC_USER" \
	| tr ' ' '\n' \
	| while IFS=':' read login group uid gid homedir shell; do
	groupadd -g $gid $group >/dev/null 2>&1 || :
	useradd -g $gid -u $uid -d $homedir -s $shell $login >/dev/null 2>&1 || :
	usermod -G $group $login || :
	done
